<template>
  <!-- 项目列表 -->
  <div style="height:520px">
    <FilterTable
      ref="infoActivityFT"
      :list="initForm"
      height="450"
      :columns="columns"
      :isSelectColumn="false"
      :dataSource="dataSource"
      :params="flterValue"
      :isToperInfo="false"
      :formType="value.type"
      :datakey="'record'"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_projram_commonForm_infoAvtivity_01"
    >
      <template slot="controls" v-if="value.type!=='show'">
        <el-button
          v-if="this.value.rowData == null || this.value.rowData.programIssuedChannel != 25301001 || this.flag == 'push'"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="openDialog(null,'add')"
        >新增</el-button>
      </template>
    </FilterTable>
    <!-- 经销商弹窗 -->
    <BaseDialog
      title="添加项目"
      :visible.sync="visibleDialog"
      width="800px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <addMadal
        ref="infoActiveDialogA"
        v-model="initModal"
        :rowData="formData"
        @close="closeDialog"
        @saveData="save"
      />
    </BaseDialog>
  </div>
</template>

<script>
import addMadal from './infoActivityDialog';
import { dictionary } from '@/utils/dictMixin';
import { selectPageBySqlActive } from '@/api/cms-api/projectOperating/program/push';
import { formatdateByDay } from '@/utils';

// import { activityDetail } from '@/api/community/activity';
// import { getExercise } from '@/api/community/activity';
export default {
  mixins: [dictionary],
  components: {
    addMadal
  },
  props: {
    value: {
      type: Object,
      required: true
    },
    flag: {
      type: String
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      activityDialogData: {},
      visibleDialog: false,
      arr: {},
      initModal: {},
      formValue: [],
      flterValue: {}, //参数
      initForm: [],
      columns: this.creatHeader(),
      // fetchParams: getExercise, //api 接口
      dataSource: [],
      formData: {},
      index: ''
    };
  },
  mounted() {
    console.log('www', this.value.rowData);
    console.log(this.flag);
    // console.log('infoActivity1:', this.value); //获取到行id
    //请求接口进行赋值，自己写吧
    //如果传入参数不为空，则说明是修改进入，
    if (this.value != null && (this.value.type == 'edit' || this.value.type == 'show')) {
      // console.log('infoActivity2:', this.value);
      this.init();
    }
  },
  methods: {
    //修改时，初始化页面数据

    async init() {
      //循环为表单赋值

      //需要确认initForm数组数据,目的是要添加多条记录 this.$refs.InfoBaseRef.formValue.infoActivityFT

      // console.log('infoActivity3:initForm:', this.initForm, 'this.arr=', this.arr, 'this.value', this.value);
      this.arr.modelId = this.value.rowData['modelId'];
      this.arr.modelName = this.value.rowData['modelName'];
      this.arr.projectProgramId = this.value.rowData['projectProgramId'];
      this.arr.currentPage = 1;
      this.arr.pageNum = 1;
      this.arr.pageSize = 10; //dataSource不支持分页

      const res = await selectPageBySqlActive(this.arr);
      // debugger
      // console.log(res.data, 'res-infoActivity');

      if (res.resultCode === 200) {
        // debugger
        // this.$notify.success({title: '提示信息',message:'getData成功!'});
        //  PROJECT_START_DATE PROJECT_END_DATE
        var result = res.data.records;
        //  console.log("a=",result[0]['projectStartDate']);
        // console.log(" =",result[0].fieldName)
        for (var i = 0; i < result.length; i++) {
          result[i].hdzq = this.formatDates(result[i]['projectStartDate']) + '~' + this.formatDates(result[i]['projectEndDate']);
        }

        this.dataSource = result; //res.data.records;
        this.formValue = this.dataSource;
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || 'getData失败!' });
      }
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            if (this.value.rowData == null || (this.value.rowData != null && this.value.rowData.programIssuedChannel != 25301001) || this.flag == 'push') {
              return (
                <div>
                  <el-button size="mini" type="text" onClick={() => this.delHandle(props.$index, 'del')}>
                    删除
                  </el-button>
                  <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit', props.$index)}>
                    编辑
                  </el-button>
                </div>
              );
            }
          }
        },
        {
          title: '项目车型ID',
          dataIndex: 'modelId',
          sorter: true,
          hidden: true
        },
        {
          title: '项目车型',
          dataIndex: 'modelName',
          sorter: true
        },
        { title: '项目地点', dataIndex: 'itemAddress', sorter: true },
        {
          title: '项目周期',
          dataIndex: 'hdzq',
          sorter: true,
          render: props => {
            return (
              <span>
                {formatdateByDay(props.row.itemStartDate)}-{formatdateByDay(props.row.itemEndDate)}
              </span>
            );
          }
        },
        {
          title: '是否必做',
          dataIndex: 'isMustDo',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isMustDo, '1004')}</span>;
          }
        },
        { title: '项目时间', dataIndex: 'itemDate', sorter: true },
        { title: '项目名称', dataIndex: 'itemName', sorter: true },
        { title: '项目主题', dataIndex: 'itemTheme', sorter: true },
        { title: '项目目的', dataIndex: 'itemPurpose', sorter: true },
        { title: '项目形式', dataIndex: 'itemForm', sorter: true }
      ];
    },
    formatDates: function(value) {
      //时间处理函数
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      if (month < 10) {
        month = '0' + month;
      }
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    openDialog(row, type) {
      this.visibleDialog = true;
      this.visible = true;
      const pram = {
        type: 'add',
        rowData: null
      };
      this.initModal = pram;
      this.formData = pram;
    },
    editHandle(row, type, index) {
      //集合的加减判断放到server端.
      this.index = index;
      this.formData = row;
      const pram = {
        type: type,
        rowData: row
      };
      this.formData = pram;
      this.visibleDialog = true;
      this.visible = true;

      // this.formValue.splice(index, 1);
    },
    delHandle(index, type) {
      //集合的加减判断放到server端.

      this.dataSource.splice(index, 1);

      // this.formValue.splice(index, 1);
    },
    save() {
      //    debugger

      this.activityDialogData = this.$refs.infoActiveDialogA.saveData;
      this.activityDialogData.status_zdj = 'add';

      if (this.formData.type == 'add') {
        let isExists = this.dataSource.find(item => item.itemName == this.activityDialogData.itemName);

        if (isExists == null || typeof isExists == 'undefined') {
          this.dataSource.push(this.activityDialogData);
        } else {
          this.$notify.warning({ title: '提示信息', message: '项目重复不可添加!' });
        }
      } else {
        this.dataSource.splice(this.index, 1);
        this.dataSource.push(this.activityDialogData);
      }

      this.formValue = Object.assign([], this.dataSource);
      // console.log("infoActivity1007",this.dataSource);
      this.visible = false;
      this.visibleDialog = this.visible; //关闭弹窗
      this.$emit('close', { visible: false });
      // if (activityDialogData.type === 'refresh') {
      //   // 重新加载
      //   this.flterValue = { ...this.flterValue };
      // }
    },
    closeDialog(data) {
      this.formValue = this.dataSource;
      //返回数据逻辑自己写
      this.visible = false;
      this.visibleDialog = false; //关闭弹窗
      if (data != undefined && data.data.type === 'refresh') {
        // 重新加载
        this.flterValue = { ...this.flterValue };
      }
    }
  }
};
</script>
